package com.example.firstfive;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.w3c.dom.DocumentType;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.logging.LogRecord;

import javax.net.ssl.HttpsURLConnection;


public class MainActivity extends AppCompatActivity implements Runnable{
 private static final String TAG="提示";
 private float dollarRate=0.12f;
 private float euroRate=0.23f;
 private float wonRate=123;
 Handler handler;
 Runnable runnable;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //加载之前的汇率数据
       SharedPreferences sharedPreferences = getSharedPreferences("myrate",
               Activity.MODE_PRIVATE);
        dollarRate=sharedPreferences.getFloat("dollar_rate",0.0f);
        euroRate=sharedPreferences.getFloat("euro_rate",0.0f);
        wonRate=sharedPreferences.getFloat("won_rate",0.0f);


            //开启
            Thread t = new Thread(this);
            t.start() ;

            handler = new Handler(Looper.myLooper()) {

                @Override
                public void handleMessage(@NonNull Message msg){
                    //super.handleMessage(msg);
                    if (msg.what==7) {
                        Bundle bundle =(Bundle)msg.obj;
                        dollarRate=bundle.getFloat("web-dollar");
                        euroRate=bundle.getFloat("web-euro");
                        wonRate=bundle.getFloat("web-won");
                        TextView  show =findViewById(R.id.result);
                        show.setText("updated");


                    }
                super.handleMessage(msg);

            }

        };

    }
    public void click(View btn){
        EditText input =findViewById(R.id.rmb);
        String s= input.getText().toString();
       Log.i(TAG, "click: ");
        if(s.length()==0)
        { Toast.makeText(this,"请输入数据",Toast.LENGTH_LONG).show();
            return;
        }
        //进行计算
        Log.i(TAG, "click: 计算 ");
        float inp =Float.parseFloat(s);
        float r=0.0f;
        if(btn.getId()==R.id.b1){
            r=inp*dollarRate;
        }else if (btn.getId()==R.id.b2)
            {r=inp*euroRate;}
        else {r=inp*wonRate;}
        //显示结果
        TextView  show =findViewById(R.id.result);
        show.setText("兑换为："+String.valueOf(r));

    }
    //将汇率传入修改界面
    public void open(View btn){
        openMain2();
    }

    private void openMain2() {
        Log.i(TAG,"open :打开新窗口");
        Intent intent = new Intent(this,MainActivity2.class);
        intent.putExtra("dollar_key",dollarRate);
        intent.putExtra("euro_key",euroRate);
        intent.putExtra("won_key",wonRate);

        Log.i(TAG,"open:dollar="+dollarRate);
        Log.i(TAG,"open:euro="+euroRate);
        Log.i(TAG,"open:won="+wonRate);
        //startActivity(intent);
        startActivityForResult(intent,1);//requestcode ,resultCode确定返回的是什么数据项
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.my_menu,menu);
        return true;
    }
//菜单按键处理
    @Override
    public boolean  onOptionsItemSelected(@NonNull MenuItem item) {
         if(item.getItemId()==R.id.menu_set){
           openMain2() ;//自己写的打开页面的方法
         }return super.onOptionsItemSelected(item);
    }
//接收返回数据区
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(requestCode==1&&resultCode==2) {
            //汇率修改页面返回的数据，data中包含bundle对象
            Bundle bdl = data.getExtras();
            //拆分放入的数据
            dollarRate = bdl.getFloat("dollar_key1",0.1f);
            euroRate = bdl.getFloat("euro_key1",0.1f);
            wonRate = bdl.getFloat("won_key1",0.1f);
           // Log.i(TAG,"");

            //保存新的汇率数据到sharep..
            SharedPreferences sp = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putFloat("dollar-rate", dollarRate);
            editor.putFloat("euro-rate", euroRate);
            editor.putFloat("won_rate", wonRate);
            editor.apply();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void run() {

    //发送时延
     Log.i(TAG,"run:run().....");
      for(int i=1;i<3;i++){
          Log.i(TAG,"run:i="+i);
          try{Thread.sleep(6000);
            //  handler.postDelayed(this,6000);
           } catch (InterruptedException e) {
              e.printStackTrace();
          }
      } //用于保存获取的汇率
         Bundle bd1=new Bundle() ;

       //获取网络数据
        URL url=null;
        try{
            url=new URL("https://www.usd-cny.com/icbc.htm");
            HttpURLConnection http =(HttpURLConnection) url.openConnection();
            InputStream in= http.getInputStream();
            String html= inputStream2String(in);
            Log.i(TAG,"run:html="+html);

          }catch (MalformedURLException e){
             e.printStackTrace() ;
        }catch(IOException e){
        e.printStackTrace(); }

        //使用JSOUP获取页面元素
        try{
            Document doc = Jsoup.connect("https://www.usd-cny.com/bankofchina.htm").get();
           Log.i(TAG,"run:title="+doc.title());
           Element  table =doc.getElementsByTag("table").first() ;
           Elements trs =table.getElementsByTag("tr");
           trs.remove(0);
           for(Element  tr: trs){
               Elements tds = tr.getElementsByTag("td");
               if(tds.size()>0){
                   //提取数据
                   Element td1=tds.first();
                   Element td2=tds.last();
                   Log.i(TAG,"run:"+td1.text()+"-->"+td2.text());
                       String str1=td1.text();
                       String str2=td2.text();
                       Log.i(TAG,"run"+str1+"-->"+str2);
                       if("欧元".equals(str1)){
                           bd1.putFloat("web-euro",100f/Float.parseFloat(str2) );
                       }else if ("美元".equals(str1) ){
                           bd1.putFloat("web-dollar",100f/Float.parseFloat(str2));
                       }else if ("韩元".equals(str1) ){
                           bd1.putFloat("web-won",100f/Float.parseFloat(str2));}
                   }

               }

           //获取TD中的数据

        }catch (IOException e){
            e.printStackTrace() ;
        }
        //获取msg对象，用于返回主线程
        Message msg= handler.obtainMessage(7,bd1);
        //msg.obj= "hello from msg";
        handler.sendMessage(msg);

        Log.i(TAG,"run:sendMessage");


    }

    private String  inputStream2String(InputStream inputStream)
      throws IOException  {
        final int bufferSize =1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in =new InputStreamReader(inputStream,"gb2312");
        while(true){
            int rsz = in.read(buffer,0,buffer.length);
            if(rsz<0)break;
            out.append(buffer,0,rsz);
        }return out.toString();

    }
}
